package com.music.service.impl;

import com.baidu.aip.face.AipFace;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.music.dao.UserMapper;
import com.music.entity.User;
import com.music.service.BaiduFaceService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.servlet.http.HttpServletRequest;
import java.io.DataInput;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class BaiduFaceServiceImpl implements BaiduFaceService {


    @Autowired
    AipFace client;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpServletRequest request;

    /**
     * 创建用户组 - 组 对标 工程
     * @param groupId 组id
     */
    @Override
    public void groupAdd(String groupId) {
        // 创建用户组
        JSONObject res = client.groupAdd(groupId, new HashMap<String, String>());
        System.out.println(res.toString(2));
    }

    /**
     * 人脸注册
     * @param userPhone 用户手机号
     * @param groupId 人员所在组
     * @param userName 人员名称
     * @param imgBase64 即将被注册的人脸图片
     * @return face_token 人脸图片的唯一标识
     */
    @Override
    public boolean faceSign(String userPhone, String groupId, String userName, String imgBase64) {
        HashMap<String, String> options = new HashMap<>(4);
        options.put("user_info", userName);
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "APPEND");

        String imageType = "BASE64";

        // 人脸注册
        JSONObject res = client.addUser(imgBase64, imageType, groupId, userPhone, options);
        System.out.println(res.toString(2));
        String faceId = null;
        if (res.getInt("error_code")  == 0) {
            faceId = res.getJSONObject("result").getString("face_token");
        }

        return faceId != null && !"".equals(faceId.trim());
    }

    /**
     * 人脸认证
     * @param groupId 人员所在组
     * @param imgBase64 即将被核验的人脸图片
     */
    @Override
    public boolean faceSearch(String groupId, String imgBase64) {
        HashMap<String, String> options = new HashMap<>(6);
        options.put("max_face_num", "1");
        options.put("match_threshold", "80");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "NORMAL");
        //options.put("user_id", userId);
        options.put("max_user_num", "1");

        String imageType = "BASE64";
        JSONObject res = client.search(imgBase64,imageType,groupId,options);
        int errCode = res.getInt("error_code");

        JSONObject result = (JSONObject) res.get("result");
        String userPhone = null;
        JSONArray jsonArray = result.getJSONArray("user_list");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            userPhone = (String) jsonObject.get("user_id");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("userPhone",userPhone);
        List<User> userList = userMapper.findUserByConditions(map);
        Optional.ofNullable(userList).ifPresent(list->{
            request.getSession().setAttribute("user",list.get(0));
        });


        return errCode == 0;
    }

    /**
     *  人脸删除
     * @param userId 人员id
     * @param groupId 人员所在组
     * @param faceToken 人脸图片的唯一标识(人脸注册时会返回)
     */
    @Override
    public void faceUninstall(String userId, String groupId, String faceToken) {
        JSONObject res = client.faceDelete(userId, groupId, faceToken, new HashMap<String, String>());
        System.out.println(res.toString(2));
    }

    /**
     * 用户删除
     * @param userId 人员id
     * @param groupId 人员所在组
     */
    @Override
    public void userDelete(String userId, String groupId) {
        // 删除用户
        JSONObject res = client.deleteUser(groupId, userId, new HashMap<>());
    }
}
